# coding: utf-8
'''
神经网络的推理处理
'''
import pickle
import numpy as np

import sys, os

# 获取当前文件路径
current_file_path = os.path.abspath(__file__)
# 获取当前文件的上一级目录路径
parent_dir = os.path.dirname(os.path.dirname(current_file_path))
# 将上一级目录添加到sys.path中
sys.path.append(parent_dir)


from dataset.mnist import load_mnist
from util.fn import sigmoid, softmax

def get_data():
    '''
    获取数据
    '''
    (x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, flatten=True, one_hot_label=False)
    return x_test, t_test

def init_network():
    '''
    初始化神经网络
    '''
    # sample_weight.pkl 是训练好的权重和偏置
    with open("../dataset/sample_weight.pkl", 'rb') as f:
        network = pickle.load(f)
    return network

def predict(network, x):
    '''
    计算神经网络的输出

    return y 以NumPy数组的形式输出各个标签对应的概率
    '''
    W1, W2, W3 = network['W1'], network['W2'], network['W3']
    b1, b2, b3 = network['b1'], network['b2'], network['b3']

    a1 = np.dot(x, W1) + b1
    z1 = sigmoid(a1)
    a2 = np.dot(z1, W2) + b2
    z2 = sigmoid(a2)
    a3 = np.dot(z2, W3) + b3
    y = softmax(a3)

    return y


def main():
    x, t = get_data()
    network = init_network()
    accuracy_cnt = 0
    for i in range(len(x)):
        y = predict(network, x[i])
        # 取出概率列表中的最大值的索引（第几个元素的概率最高），作为预测结果
        p = np.argmax(y)
        if p == t[i]: # 索引即是要识别的数字
            accuracy_cnt += 1
    print("Accuracy:" + str(float(accuracy_cnt) / len(x)))

if __name__ == '__main__':
    main()


